package cn.edu.ncut.cs.springboot.springbootmybatisplus.service;

import cn.edu.ncut.cs.springboot.springbootmybatisplus.entity.Course;
import cn.edu.ncut.cs.springboot.springbootmybatisplus.entity.User;
import cn.edu.ncut.cs.springboot.springbootmybatisplus.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserDetailService implements UserDetailsService{
    @Autowired
    private IUserService userService; // 注入IUserService以使用其方法

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> Username = userService.getByUsername(username);
        if (Username.isEmpty()) {
            System.out.println("User not found with username: " + username);
            throw new UsernameNotFoundException("User not found: " + username);
        }
        User userOptional = Username.get();
        List<GrantedAuthority> authorities = Collections.singletonList(
                new SimpleGrantedAuthority(userOptional.getRole()) // 假设User类有一个getRole()方法返回角色字符串
        );

        return org.springframework.security.core.userdetails.User.builder()
                .username(userOptional.getUsername())
                .password(userOptional.getPassword())
                .authorities(authorities)
                .build();
    }
}
